import React, { Component,Fragment } from 'react'
import List from './list'
import store from '../../../store/redux-thunk/'
import { changeIptAction,changeItemAction,setListAction } from '../../../store/redux-thunk/actionCreators'
import './list.css'

export default class TodoList extends Component{
    constructor(props){
        super(props);
        this.state = store.getState()
        this.delfun = this.delfun.bind(this)
        this.addHandle = this.addHandle.bind(this)
        this.changeIpt = this.changeIpt.bind(this)
        this.storeChange = this.storeChange.bind(this)
        store.subscribe(this.storeChange)//订阅，store每次变化都会触发 this.storeChange
    }
    render(){
        return (<Fragment>
            <div>
                <label htmlFor="todoTxt">备忘录：</label>
                <input id="todoTxt" 
                    onChange={this.changeIpt} 
                    ref={(input)=>{this.todoIpt = input}} 
                    placeholder="please input" 
                    value={this.state.iptVal}
                />
                <button onClick={this.addHandle}>添加</button>
            </div>
            <div>
                <List 
                    data={this.state.list}
                    delFun={this.delfun}
                />
            </div>
        </Fragment>);
    }
    changeIpt(){
        const action = changeIptAction(this.todoIpt.value)
        store.dispatch(action);
    }
    addHandle(){
        let list = this.state.list
        if(this.state.iptVal){
            list.push(this.state.iptVal)
            const action = changeItemAction(list)
            store.dispatch(action)
            const action1 = changeIptAction("")
            store.dispatch(action1)
        }
    }
    delfun(idx){
        let list = this.state.list
        list.splice(idx,1)
        const action = changeItemAction(list)
        store.dispatch(action)
    }
    storeChange(){
       this.setState(store.getState())
    }
    componentDidMount(){
        const action = setListAction();
        store.dispatch(action)
    }
}
